package com.sxjh.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.extra.cglib.CglibUtil;
import com.sxjh.entity.Settlement;
import com.sxjh.entity.bo.Finance7SettleBo;
import com.sxjh.entity.param.Finance7List3Param;
import com.sxjh.entity.param.Finance7SettleParam;
import com.sxjh.entity.result.Finance7List3Result;
import com.sxjh.entity.result.Finance7SettleAllResult;
import com.sxjh.entity.result.Finance7SettleResult;
import com.sxjh.mapper.SettlementMapper;
import com.sxjh.service.SettlementService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 结算列表 服务实现类
 * </p>
 *
 * @author zixin
 * @since 2021-08-03
 */
@Service
public class SettlementServiceImpl extends ServiceImpl<SettlementMapper, Settlement> implements SettlementService {

  @Autowired
  private SettlementMapper settlementMapper;

  @Override
  public List<Finance7List3Result> list(Finance7List3Param param) {
    List<Finance7List3Result> list = settlementMapper.list(param);
    for (Finance7List3Result result : list) {
      result.setMoneySum(result.getStatementPrice().multiply(result.getStatementPrice()).setScale(2, BigDecimal.ROUND_DOWN));
    }
    return list;
  }

  // 处理焦炭结算数据
  @Override
  public Finance7SettleAllResult settle(Finance7SettleParam param) {
    Finance7SettleAllResult result = new Finance7SettleAllResult();
    LocalDate settleDate = LocalDate.now(); // 结算日期
    result.setSettleDate(settleDate);
    // 所有焦炭物料  1 冶金焦炭（干熄焦）,2 冶金焦炭（湿熄焦）,3 一级冶金焦（干熄焦）,7 定制一级冶金焦（干熄焦）,
    // 9 定制准一冶金焦（干熄焦）,10 定制准一冶金焦（湿熄焦）,11 10-25mm焦粒（干熄焦）,13 10-30mm焦粒（干熄焦）,15 0-10mm焦粉（干熄焦）
    List<Finance7SettleBo> list = settlementMapper.settle(param);
    LocalDate startDate = list.size() > 0 ? list.get(0).getDate() : settleDate; // 最开始的时间
    LocalDate endDate = settleDate; // 最后的时间
    List<Finance7SettleResult> results = new ArrayList<>();
    BigDecimal minus = new BigDecimal(-1);
    // 合计
    Finance7SettleResult total = new Finance7SettleResult();
    total.setNetWeight(new BigDecimal(0));
    total.setWeighbridgeWeight(new BigDecimal(0));
    total.setVehCount(0);
    total.setMoneySum(new BigDecimal(0));
    // 扣款明细
    Finance7SettleResult dt = new Finance7SettleResult();
    dt.setAshValue(new BigDecimal(0));
    dt.setSulfurValue(new BigDecimal(0));
    dt.setM40Value(new BigDecimal(0));
    dt.setM10Value(new BigDecimal(0));
    dt.setCsrValue(new BigDecimal(0));
    dt.setCriValue(new BigDecimal(0));
    dt.setVolatilizeValue(new BigDecimal(0));
    dt.setMoneySum(new BigDecimal(0));
    for (Finance7SettleBo bo : list) {
      // 取开始时间
      if (startDate.compareTo(bo.getDate()) == 1) {
        startDate = bo.getDate();
      }
      if (endDate.compareTo(bo.getDate()) == -1) {
        endDate = bo.getDate();
      }
      Finance7SettleResult item = CglibUtil.copy(bo, Finance7SettleResult.class);
      // 结算量=净重进行扣水（净重=生成结算单时填写的最终结算数量）
      BigDecimal netWeight = bo.getStatementQuantity(); // 净重
      item.setNetWeight(netWeight); // 净重
      BigDecimal weighbridgeWeight = netWeight; // 结算数量（默认等于净重）
      // 补途处理
      // 补途1‰
      if (bo.getComplementaryWay() == 1) {
        weighbridgeWeight = weighbridgeWeight.multiply(new BigDecimal(0.999));
      }
      // 补途4%
      else if (bo.getComplementaryWay() == 2) {
        weighbridgeWeight = weighbridgeWeight.multiply(new BigDecimal(0.96));
      }
      // 扣水
      // 百分比
      BigDecimal bfb = new BigDecimal(100).subtract(bo.getWaterValue().subtract(bo.getWater()));
      // 计价水
      BigDecimal jjs = (new BigDecimal(100).subtract(bo.getWaterValue())).divide(new BigDecimal(100).subtract(bo.getWater()), 2, BigDecimal.ROUND_DOWN);
      switch (bo.getDeductWaterType()) {
        // 百分比±
        case 0:
          weighbridgeWeight = weighbridgeWeight.multiply(bfb).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);
          break;
          // 百分比-
        case 1:
          if (bfb.compareTo(new BigDecimal(100)) == -1) {
            weighbridgeWeight = weighbridgeWeight.multiply(bfb).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);
          }
          break;
          // 计价水+-
        case 2:
          weighbridgeWeight = weighbridgeWeight.multiply(jjs);
          break;
          // 计价水-
        case 3:
          if (jjs.compareTo(new BigDecimal(1)) == -1) {
            weighbridgeWeight = weighbridgeWeight.multiply(jjs);
          }
          break;
          // 干基
        case 4:
          weighbridgeWeight = weighbridgeWeight.multiply(new BigDecimal(100).subtract(bo.getWaterValue())).divide(new BigDecimal(100), BigDecimal.ROUND_DOWN);
          break;
      }
      item.setWeighbridgeWeight(weighbridgeWeight);
      // 灰分扣奖
      BigDecimal ashDeduct = new BigDecimal(0);
      if (bo.getAshValue().compareTo(bo.getAsh()) == 1) {
        BigDecimal bigDecimal = bo.getAshValue().subtract(bo.getAsh());
        ashDeduct = bigDecimal.multiply(bo.getAshDiscount()).divide(bo.getAshScale(), 2, BigDecimal.ROUND_DOWN);
      }
      item.setAshDeduct(ashDeduct.multiply(minus));
      // 硫分扣奖
      BigDecimal sulfurDeduct = new BigDecimal(0);
      if (bo.getSulfurValue().compareTo(bo.getSulfur()) == 1) {
        BigDecimal bigDecimal = bo.getSulfurValue().subtract(bo.getSulfur());
        sulfurDeduct = bigDecimal.multiply(bo.getSulfurDiscount()).divide(bo.getSulfurScale(), 2, BigDecimal.ROUND_DOWN);
      }
      item.setSulfurDeduct(sulfurDeduct.multiply(minus));
      // 挥发分扣奖
      BigDecimal volatilizeDeduct = new BigDecimal(0);
      if (bo.getVolatilizeValue().compareTo(bo.getVolatilize()) == 1) {
        BigDecimal bigDecimal = bo.getVolatilizeValue().subtract(bo.getVolatilize());
        sulfurDeduct = bigDecimal.multiply(bo.getSulfurDiscount()).divide(bo.getSulfurScale(), 2, BigDecimal.ROUND_DOWN);
      }
      item.setVolatilizeDeduct(volatilizeDeduct);
      // m40扣奖
      BigDecimal m40Deduct = new BigDecimal(0);
      if (bo.getM10Value().compareTo(m40Deduct) == 1 && bo.getM40Value().compareTo(bo.getM40()) == -1) {
        BigDecimal bigDecimal = bo.getM40().subtract(bo.getM40Value());
        m40Deduct = bigDecimal.multiply(bo.getM40Discount()).divide(bo.getM40Scale(), 2, BigDecimal.ROUND_DOWN);
      }
      item.setM40Deduct(m40Deduct.multiply(minus));
      // m10扣奖
      BigDecimal m10Deduct = new BigDecimal(0);
      if (bo.getM10Value().compareTo(bo.getM10()) == 1) {
        BigDecimal bigDecimal = bo.getM10Value().subtract(bo.getM10());
        m10Deduct = bigDecimal.multiply(bo.getM10Discount()).divide(bo.getM10Scale(), 2, BigDecimal.ROUND_DOWN);
      }
      item.setM10Deduct(m10Deduct.multiply(minus));
      // csr扣奖
      BigDecimal csrDeduct = new BigDecimal(0);
      if (bo.getCsrDiscount().compareTo(csrDeduct) == 1 && bo.getCsrValue().compareTo(bo.getCsr()) == -1) {
        BigDecimal bigDecimal = bo.getCsr().subtract(bo.getCsrValue());
        csrDeduct = bigDecimal.multiply(bo.getCsrDiscount()).divide(bo.getCsrScale(), 2, BigDecimal.ROUND_DOWN);
      }
      item.setCsrDeduct(csrDeduct.multiply(minus));
      // csi扣奖
      BigDecimal criDeduct = new BigDecimal(0);
      if (bo.getCriValue().compareTo(bo.getCri()) == 1) {
        BigDecimal bigDecimal = bo.getCriValue().subtract(bo.getCri());
        criDeduct = bigDecimal.multiply(bo.getCriDiscount()).divide(bo.getCriScale(), 2, BigDecimal.ROUND_DOWN);
      }
      item.setCriDeduct(criDeduct.multiply(minus));
      // 焦沫扣奖
      BigDecimal tonnage = new BigDecimal(0); // 含粉吨位
      BigDecimal foamDeduct = new BigDecimal(0); // 焦沫扣总价
      if (bo.getFoamValue().compareTo(bo.getFoam()) == 1) {
        BigDecimal bigDecimal = bo.getFoamValue().subtract(bo.getFoam());
        tonnage = bigDecimal.multiply(weighbridgeWeight);
        foamDeduct = tonnage.multiply(bo.getPrice()).divide(new BigDecimal(2), 2, BigDecimal.ROUND_DOWN);
      }
      item.setTonnage(tonnage);
      item.setFoamDeduct(foamDeduct);
      // 付款类别处理（承兑加价2%）
      if (bo.getPaymentType() == 1) {
        bo.setPrice(bo.getPrice().multiply(new BigDecimal(1.02).setScale(0, BigDecimal.ROUND_DOWN)));
      }
      // 合同种类处理
      BigDecimal freight = new BigDecimal(0);
      // 车板
      if (bo.getContractType() == 0) {
        freight = weighbridgeWeight.multiply(bo.getFreight());
      }
      // 两票包到
      else if (bo.getContractType() == 2) {
        freight = weighbridgeWeight.multiply(bo.getFreight()).multiply(new BigDecimal(-1));
      }
      // 结算价格 = 合同价-各种扣奖
      BigDecimal statementPrice = bo.getPrice().subtract(ashDeduct).subtract(sulfurDeduct)
              .subtract(m40Deduct).subtract(m10Deduct).subtract(csrDeduct).subtract(criDeduct).subtract(volatilizeDeduct);
      // 结算总金额 = 结算价格*结算数量-焦沫扣奖+（+/-运费）
      BigDecimal moneySum = statementPrice.multiply(weighbridgeWeight)
              .subtract(foamDeduct).add(freight).setScale(2, BigDecimal.ROUND_DOWN);
      item.setStatementPrice(statementPrice);
      item.setMoneySum(moneySum);
      results.add(item);
      // 计算合计
      total.setNetWeight(total.getNetWeight().add(item.getNetWeight()));
      total.setWeighbridgeWeight(total.getWeighbridgeWeight().add(item.getWeighbridgeWeight()));
      total.setVehCount(total.getVehCount() + item.getVehCount());
      total.setMoneySum(total.getMoneySum().add(item.getMoneySum()));
      // 计算扣款明细
      dt.setAshValue(dt.getAshValue().add(item.getWeighbridgeWeight().multiply(item.getAshDeduct())));
      dt.setSulfurValue(dt.getSulfurValue().add(item.getWeighbridgeWeight().multiply(item.getSulfurDeduct())));
      dt.setM40Value(dt.getM40Value().add(item.getWeighbridgeWeight().multiply(item.getM40Deduct())));
      dt.setM10Value(dt.getM10Value().add(item.getWeighbridgeWeight().multiply(item.getM10Deduct())));
      dt.setCsrValue(dt.getCsrValue().add(item.getWeighbridgeWeight().multiply(item.getCsrDeduct())));
      dt.setCriValue(dt.getCriValue().add(item.getWeighbridgeWeight().multiply(item.getCriDeduct())));
      dt.setVolatilizeValue(dt.getVolatilizeValue().add(item.getWeighbridgeWeight().multiply(item.getVolatilizeDeduct())));
    }
    if (results.size() > 0) {
      result.setContractNumber(results.get(0).getContractNumber());
      result.setMaterialName(results.get(0).getMaterialName());
      result.setInspection(results.get(0).getInspection());
      result.setContractType(results.get(0).getInspection());
      result.setPaymentType(results.get(0).getPaymentType());
      result.setComplementaryWay(results.get(0).getComplementaryWay());
      result.setPrice(results.get(0).getPrice());
      result.setDeliverMonth(startDate.toString() + "-" + endDate.toString());
      result.setWater(results.get(0).getWater());
      result.setAsh(results.get(0).getAsh());
      result.setCri(results.get(0).getCri());
      result.setCsr(results.get(0).getCsr());
      result.setFoam(results.get(0).getFoam());
      result.setSulfur(results.get(0).getSulfur());
      result.setVolatilize(results.get(0).getVolatilize());
      result.setM10(results.get(0).getM10());
      result.setM40(results.get(0).getM40());
      // 保存合计
      results.add(total);
      // 保存明细扣款
      dt.setMoneySum(dt.getAshValue().add(dt.getSulfurValue()
              .add(dt.getM40Value()).add(dt.getM10Value())
              .add(dt.getCsrValue()).add(dt.getCriValue()).add(dt.getVolatilizeValue())));
      results.add(dt);
    }
    result.setResults(results);
    return result;
  }
}
